package cn.vshare.controller;

import cn.vshare.entity.Role;
import cn.vshare.service.PermissionSecondService;
import cn.vshare.service.RoleService;
import com.github.pagehelper.Page;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@RestController
public class RoleController {

    @Resource
    private RoleService roleService;
    @Resource
    private PermissionSecondService permissionSecondService;

    @RequestMapping(value = "getAllRole")
    public List<Role> getAllRole() {
        List<Role> roleList = roleService.queryAllRole();
        return roleList;
    }

    @RequestMapping(value = "updateInfo2Role_PermissionFirst")
    public String updateInfo2Role_PermissionFirst(String roleId, String[] id2First2Array, String[] id2Second2Array) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map2Result = new HashMap<>();
        String result = "false";

        //清空原始信息
        map.put("role_id", roleId);
        int row2delete = roleService.deletePermissionSecond2Role(map);
        //绑定角色-2级权限的新增
        if (id2Second2Array != null) {
            for (int i = 0; i < id2Second2Array.length; i++) {
                System.out.println(id2Second2Array[i]);
                map.put("id", UUID.randomUUID().toString());
                map.put("role_id", roleId);
                map.put("second_id", id2Second2Array[i]);
                int row = roleService.addPermissionSecond2Role(map);

                if (row == 1) {
                    System.out.println(i + "新增成功");
                    result = "true";//新增角色-二级权限成功
                } else {
                    System.out.println(i + "新增失败");
                    result = "false";
                    break;
                }//else结束
            }
        } else {
            System.out.println("id2First2Array.length的长度为0");
            result = "0";
        }
        return result;
    }


    @RequestMapping(value = "getPermissionSecond2Role")
    public Role getPermissionSecond2Role(String roleId) {
        Map<String, Object> map = new HashMap<>();

        map.put("r_id", roleId);
        Role role = roleService.queryPermissionSecond2Role(map);

        return role;
    }

    /**
     * 目的是存到session域,用于页面之间的数据传递,
     *
     * @param id2Role
     * @param session
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "getRoleById", method = RequestMethod.POST)
    public String getRoleById(String id2Role,
                              HttpSession session,
                              HttpServletRequest request,
                              HttpServletResponse response) throws ServletException, IOException {
        String result = "false";
        //System.out.println("id2Role====="+id2Role);
        Role role = roleService.queryRoleById(new Role(id2Role));
        session.setAttribute("role", role);//存储到Session域中
        //response.sendRedirect("h-ui/admin-role-edit.jsp");//重定向
        if (role != null) {
            result = "true";
        } else {
            result = "false";
        }
        return result;
    }


    @RequestMapping(value = "getAllRoleByPage")
    public Map<String, Object> getAllRoleByPage(int pageNum, int pageSize, String name2Role) {

        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", pageNum);//当前页码
        map.put("pageSize", pageSize);//每页显示的最大记录数
        map.put("name", name2Role);//角色名称的关键字
        Page page = roleService.queryByConditions(map);
        map.put("page", page);//list集合
        map.put("totalRecords", page.getTotal());//总记录数
        map.put("totalPages", page.getPages());//总页数
        return map;
    }


    /**
     * 1-角色的新增,
     * 2-判定对应的初始化二级权限数组的长度是否为零
     *
     * @param roleName
     * @param id2First2Array
     * @param id2Second2Array
     * @return
     */
    @RequestMapping(value = "addRole", method = RequestMethod.POST)
    public String addRole(String roleName, String[] id2First2Array, String[] id2Second2Array) {
        Map<String, Object> map = new HashMap<>();
        String result = "false";

        System.out.println("roleName====" + roleName);//t_role
        if ("".equals(id2First2Array))//防止为空字符串
            System.out.println("id2First2Array=====" + id2First2Array.length);//暂时不作处理,中间表t_role_permission_first
        if ("".equals(id2Second2Array))//防止为空字符串
            System.out.println("id2Second2Array=====" + id2Second2Array.length);//中间表t_role_permission_second

        //角色的新增
        Role role = new Role();
        role.setId(UUID.randomUUID().toString());
        role.setName(roleName);
        int row2Role = roleService.addRole(role);

        //判定新增角色是否成功
        if (row2Role == 1) {
            //新增角色成功
            //判断二级权限id2Second2Array的长度是否为零
            int row = -1;
            if (id2Second2Array.length > 0) {
                //二级权限id2Second2Array的长度大于零
                //1-查询新增角色的完整信息,获得RoleId
                Role getId2Role = roleService.queryRoleByName(roleName);//角色名称必须唯一,否则报错
                //2-向中间表t_role_permission_second中新===增角色-二级权限的多条记录

                for (int i = 0; i < id2Second2Array.length; i++) {

                    System.out.println(id2Second2Array[i]);

                    map.put("id", UUID.randomUUID().toString());
                    map.put("role_id", getId2Role.getId());
                    map.put("second_id", id2Second2Array[i]);
                    row = roleService.addPermissionSecond2Role(map);

                    if (row == 1) {
                        System.out.println(i + "新增成功");
                        result = "true";//新增角色-二级权限成功
                    } else {
                        System.out.println(i + "新增失败");
                        result = "false";
                        break;
                    }//else结束

                }//for结束

            } else {
                //二级权限id2Second2Array的长度为零
                System.out.println("id2First2Array.length的长度为0");
            }//else结束

            if (row == 0) {
                result = "false";//新增角色-二级权限失败
            } else {
                result = "true";//新增角色-二级权限成功
            }

        } else {
            //新增角色失败
            System.out.println("新增角色失败");
            result = "false";
        }

        return result;
    }

    @RequestMapping(value = "deleteRole", method = RequestMethod.POST)
    public String deleteRole(String delete2RoleId) {
        Map<String, Object> map = new HashMap<>();
        System.out.println("delete2RoleId====" + delete2RoleId);

        //清空中间表t_role_permission_second的信息
        map.put("role_id", delete2RoleId);
        int row2delete = roleService.deletePermissionSecond2Role(map);

        //删除角色
        int row = roleService.deleteRole(delete2RoleId);

        if (row == 1) {
            System.out.println("删除成功");
            return "true";
        } else {
            System.out.println("删除失败");
            return "false";
        }
    }


    //批量删除
    @RequestMapping(value = "delete2Array2Role", method = RequestMethod.POST)
    public String delete2Array2Role(@RequestBody List<String> delete2Array2RoleId) {
        System.out.println("delete2Array2RoleId====" + delete2Array2RoleId);

        Map<String, Object> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        String result = "false";
        for (int i = 0; i < delete2Array2RoleId.size(); i++) {
            //清空中间表t_role_permission_second的信息
            map.put("role_id", delete2Array2RoleId.get(i));
            int row2delete = roleService.deletePermissionSecond2Role(map);//多行数据或者没有数据可删除

            //删除角色,该操作是主因诱发异常
            int row = roleService.deleteRole(delete2Array2RoleId.get(i));
            list.add(row);
        }

        //判断是否全部删除,如果删除异常
        //如果删除异常,应该使用事物回滚,需要完善
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) == 1) {
                System.out.println("删除成功");
                result = "true";
            } else {
                System.out.println("删除失败");
                result = "false";
                break;
            }
        }
        return result;

    }


    @RequestMapping(value = "toAdmin_role_edit")
    public ModelAndView toAdmin_role_edit() {
        return new ModelAndView("h-ui/admin_role_edit");
    }

    @RequestMapping(value = "forwardRole")
    public ModelAndView forwardRole() {
        return new ModelAndView("h-ui/admin-role");
    }
    @RequestMapping(value = "forwardPermissionFirst")
    public ModelAndView forwardPermissionFirst() {
        return new ModelAndView("h-ui/admin-permission-first");
    }
    @RequestMapping(value = "forwardPermissionSecond")
    public ModelAndView forwardPermissionSecond() {
        return new ModelAndView("h-ui/admin-permission-second");
    }
    @RequestMapping(value = "forwardRole2Admin2User")
    public ModelAndView forwardRole2Admin2User() {
        return new ModelAndView("h-ui/admin-list");
    }


    @RequestMapping(value = "toAdmin_role_add")
    public ModelAndView toAdmin_role_add() {
        return new ModelAndView("h-ui/admin-role-add");
    }

    @RequestMapping(value = "toAdmin_permission_first_add")
    public ModelAndView toAdmin_permission_first_add() {
        return new ModelAndView("h-ui/admin-permission-first-add");
    }

    @RequestMapping(value = "toAdmin_permission_second_add")
    public ModelAndView toAdmin_permission_second_add() {
        return new ModelAndView("h-ui/admin-permission-second-add");
    }



}
